spmwarp.global <- function (ref, samp, init.coef, stw.par.list,
		     time, try = FALSE, smooth.param, ...)

{
  ncr <- ncol(ref)
  t.id <- 1:ncr - 0.5
  B <- bbase(t.id, 0, ncr, stw.par.list$bspl, stw.par.list$spldeg)
   
  nb <- length(init.coef)
  D <- diff(diag(nb), diff = stw.par.list$diffdeg)
  
  a <- init.coef
  
  # perform optimization
  if (smooth.param > 0) {
     samp.sm <- t(apply(samp, 1, difsm, smooth.param))
     ref.sm <- t(apply(ref, 1, difsm, smooth.param))
     Opt <- optim(a, sRMS, NULL, ref.sm, samp.sm, time, B, D, stw.par.list$lambda, stw.par.list$kappa, method="BFGS", ...)
  } else {
     Opt <- optim(a, sRMS, NULL, ref, samp, time, B, D, stw.par.list$lambda, stw.par.list$kappa, method="BFGS", ...)
  }
    
    a <- c(Opt$par)
    v <- Opt$value

    if (!try && smooth.param > 0)
      v <- sRMS(a, ref, samp, time, B, D, stw.par.list$lambda, stw.par.list$kappa)
  
  w <- time + t(B %*% a)
  h <- (ncr-0)/stw.par.list$bspl # distance between knots of B-splines
  B.deriv <- bbase(t.id, 0, ncr, stw.par.list$bspl, stw.par.list$spldeg-1)
  a.deriv <- diff(a)
  stw.w.deriv <- -t(B.deriv %*% a.deriv)/h

  list(w = w, a = a, v = v, stw.w.deriv = stw.w.deriv)
}